package com.zwk.nginxmanage.controller;

import com.zwk.nginxmanage.common.R;
import com.zwk.nginxmanage.config.UserConfig;
import com.zwk.nginxmanage.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private HttpSession session;
    @Autowired
    private UserConfig config;
    private List<User> users;

    private List<User> temps;

    @PostConstruct
    public void init(){
        this.users=this.config.getList();
    }

    @PostMapping("/login")
    public R login(@RequestBody @Valid User user){
        List<User> list=new ArrayList<>();
        if (users!=null){
            list.addAll(users);
        }
        if (temps!=null) {
            list.addAll(temps);
        }
        for (User u : list) {
            if(u.getUsername().equals(user.getUsername())&&u.getPassword().equals(user.getPassword())){
                session.setAttribute("user",u);
                return R.ok("登录成功！").put("data",true);
            }
        }
        return R.error(400,"账号或密码错误").put("data",false);
    }
}
